// ==UserScript==
// @name           FirefoxDownload_Shura.uc.js
// @namespace      FirefoxDownload_Shura.uc.js
// @description    扩展Firefox的下载界面，下载按钮右键新建下载+复制链接+另存为+自动关闭下载产生的空白标签
// @author         Shura
// @include        main
// @charset        UTF-8
// @version        1.3
// @homepageURL    http://chenxuefeng.net.cn/
// @reviewURL      https://github.com/xiuluo/UserChromeJS
// @note 		   扩展Firefox的下载界面，由Shura制作，脚本部分源于网络。
// @include        chrome://browser/content/browser.xul
// @include        chrome://mozapps/content/downloads/unknownContentType.xul
// ==/UserScript==
(function() {
    switch (location.href) {
        case "chrome://browser/content/browser.xul":
            newDownload_button(); // 下载按钮右键点击新建下载
            autoClose_blankTab();//自动关闭下载产生的about:blank
            break;
        case "chrome://mozapps/content/downloads/unknownContentType.xul":
            download_dialog_saveAs(); // 另存为
            download_dialog_showCompleteURL();// 下载弹出窗口复制下载链接
            break;
    }
    //下载按钮右键点击新建下载 by ywzhaiqi
    function newDownload_button() {
        var downloads_button_id = "downloads-button";
        var downloads_indicator_id = "downloads-indicator";
        addButtonListener(downloads_button_id);
        // 如果没成功
        if (!addButtonListener(downloads_indicator_id)) {
            var target = document.getElementById(downloads_button_id);
            var observer = new window.MutationObserver(function(mutations) {
                if (addButtonListener(downloads_indicator_id)) {
                    observer.disconnect();
                }
            });
            observer.observe(target, {
                attributes: true
            });
        }

        function addButtonListener(_buttonId) {
            var _button = document.getElementById(_buttonId);
            if (_button) {
                _button.removeEventListener("click", btnDownloads_Clicked, false);
                _button.addEventListener("click", btnDownloads_Clicked, false);
                return true;
            } else {
                return false;
            }

            function btnDownloads_Clicked(e) {
                if (e.button == 2 && !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey) {
                    e.preventDefault();
                    e.stopPropagation();
                    open_newDownload_dialog();
                }
            }
        }
		function open_newDownload_dialog() {
            window.openDialog("data:application/vnd.mozilla.xul+xml;charset=UTF-8;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLT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ajsgaSsrKSB7CiAgICAgICAgICAgICAgICAgICAgdXJscy5wdXNoKGJhdGNodXJsLnJlcGxhY2UoL1xbXGQrLVxkKygtXGQrKT9cXS8sIChpICsgIiIpLmxlbmd0aCA8IGsgPyAoZXZhbCgiMTBlIiArIChrIC0gKGkgKyAiIikubGVuZ3RoKSkgKyAiIikuc2xpY2UoMikgKyBpIDogaSkpOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgZG9jdW1lbnQucXVlcnlTZWxlY3RvcigiI3VybHMiKS52YWx1ZSA9IHVybHMuam9pbigiXG4iKTsKICAgICAgICAgICAgfSBlbHNlIHsKICAgICAgICAgICAgICAgIGRvY3VtZW50LnF1ZXJ5U2VsZWN0b3IoIiN1cmxzIikudmFsdWUgPSBiYXRjaHVybDsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBkb2N1bWVudC5xdWVyeVNlbGVjdG9yKCJ0ZXh0Ym94IikuYWRkRXZlbnRMaXN0ZW5lcigia2V5dXAiLCBQYXJzZVVSTHMsIGZhbHNlKTsKICAgICAgICBkb2N1bWVudC5xdWVyeVNlbGVjdG9yKCJidXR0b24iKS5hZGRFdmVudExpc3RlbmVyKCJjb21tYW5kIiwgZnVuY3Rpb24gKCkgewogICAgICAgICAgICBkb2N1bWVudC5xdWVyeVNlbGVjdG9yKCIjdXJscyIpLnZhbHVlLnNwbGl0KCJcbiIpLmZvckVhY2goZnVuY3Rpb24gKHVybCkgewogICAgICAgICAgICAgICAgb3BlbmVyLnNhdmVVUkwodXJsICwgbnVsbCwgbnVsbCwgbnVsbCwgdHJ1ZSwgbnVsbCwgZG9jdW1lbnQpOwogICAgICAgICAgICB9KTsKICAgICAgICAgICAgY2xvc2UoKQogICAgICAgIH0sIGZhbHNlKTsKICAgICAgICBkb2N1bWVudC5xdWVyeVNlbGVjdG9yKCJ0ZXh0Ym94IikudmFsdWUgPSAob3BlbmVyLm9wZW5lciB8fCB3aW5kb3cub3BlbmVyKS5yZWFkRnJvbUNsaXBib2FyZCgpOwogICAgICAgIFBhcnNlVVJMcygpOwogICAgICAgIF1dPgogICAgPC9zY3JpcHQ+Cjwvd2luZG93Pg==",
            "name", "top=" + (window.screenY + 50) + ",left=" + (window.screenX + 50));
        }
    }
    //复制真实完全地址
    function download_dialog_showCompleteURL() {
    var copyURL = document.documentElement.getButton("extra2");
    copyURL.hidden=false;
    copyURL.label="\u590d\u5236\u94fe\u63a5";
    copyURL.setAttribute("oncommand",  'Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper).copyString(dialog.mLauncher.source.spec);document.documentElement.getButton("extra2").label="\u590d\u5236\u6210\u529f";')
    }
    //另存为
   function download_dialog_saveAs(){
   var saveas = document.documentElement.getButton("extra1");
   saveas.setAttribute("hidden", "false");
   saveas.setAttribute("label", "\u53E6\u5B58\u4E3A");
   saveas.setAttribute("oncommand", 'var mainwin = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser"); mainwin.eval("(" + mainwin.internalSave.toString().replace("let ", "").replace("var fpParams", "fileInfo.fileExt=null;fileInfo.fileName=aDefaultFileName;var fpParams") + ")")(dialog.mLauncher.source.asciiSpec, null, (document.querySelector("#locationtext") ? document.querySelector("#locationtext").value : dialog.mLauncher.suggestedFileName), null, null, null, null, null, null, mainwin.document, 0, null);close()');
    }
    //自动关闭下载产生的空白标签
    function autoClose_blankTab() {
        eval("gBrowser.mTabProgressListener = " + gBrowser.mTabProgressListener.toString().replace(/(?=var location)/, '\
            if (aWebProgress.DOMWindow.document.documentURI == "about:blank"\
            && aRequest.QueryInterface(nsIChannel).URI.spec != "about:blank") {\
            aWebProgress.DOMWindow.setTimeout(function() {\
            !aWebProgress.isLoadingDocument && aWebProgress.DOMWindow.close();\
            }, 100);\
            }\
        '));
    }
})();